import java.io.IOException;
import com.tinkerforge.AlreadyConnectedException;
import com.tinkerforge.BrickletRotaryPoti;
import com.tinkerforge.IPConnection;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;

/**
 * Component which allows you to control the volume of your (linux) pc with a tinkerforge rotary poti bricklet.
 * This components uses the alsamixer, which is default on most linux systems. 
 * If you haven't got a linux machine or aren't using alsamixer, don't use this component! 
 * 
 * @author Michael Schaer
 * @author Raphael Haenni
 *
 */
public class VolumeController {
	
	private int port;
	private String host, rotaryPotiUID;
	private BrickletRotaryPoti rotaryPoti;
	private static final short CALLBACK_PERIOD_VALUE = 50, ROTARY_VOLUME_VALUE = 150, ROTARY_VOLUME_FACTOR = 3;

	/**
	 * Creates a new VolumeController.
	 * @param host The host address of the master brick.
	 * @param port The port address of the master brick.
	 * @param rotaryPotiUID The UID of the rotary poti bricklet.
	 */
	public VolumeController(String host, int port, String rotaryPotiUID) throws IOException, AlreadyConnectedException, TimeoutException, NotConnectedException {
		this.host = host;
		this.port = port;
		this.rotaryPotiUID = rotaryPotiUID;
		
		IPConnection ipc = new IPConnection();
		ipc.connect(this.host, this.port);
		this.rotaryPoti = new BrickletRotaryPoti(this.rotaryPotiUID, ipc);
        rotaryPoti.setPositionCallbackPeriod(VolumeController.CALLBACK_PERIOD_VALUE);
        rotaryPoti.addPositionListener(new BrickletRotaryPoti.PositionListener() {
        	
			@Override
			public void position(short position) {
				Integer volume = ((position + VolumeController.ROTARY_VOLUME_VALUE) / VolumeController.ROTARY_VOLUME_FACTOR);
				StringBuilder sb = new StringBuilder(volume.toString());
				sb.append("%");
				System.out.println("amixer sset 'Master' " + sb.toString());
				try {
					Runtime.getRuntime().exec("amixer sset 'Master' " + sb.toString());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
